package com.lb.shopguide.ui.fragment.guide;

import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CacheDiskUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.QiniuInfo;
import com.lb.shopguide.entity.UserBean;
import com.lb.shopguide.event.guide.UserInfoChangeEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.shopguide.ui.activity.GuideActivity;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.dialog.DialogSelectPic;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.lb.LbStringUtils;
import com.lb.shopguide.util.lb.LogoutHelper;
import com.lb.shopguide.util.lb.SelectPicUtil;
import com.lb.shopguide.util.pic.GlideCleanUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/5/31.
 */

public class FragmentSettings extends BaseCommonFragment implements TakePhoto.TakeResultListener, InvokeListener {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tvNickname)
    TextView tvNickname;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_real_name)
    TextView tvRealName;
    @BindView(R.id.rl_avatar)
    RelativeLayout layoutAvatar;
    @BindView(R.id.layout_clear_cache)
    RelativeLayout layoutCleanCache;
    @BindView(R.id.layout_version)
    RelativeLayout layoutVersion;
    @BindView(R.id.rl_nickname)
    RelativeLayout layoutNickname;
    @BindView(R.id.btn_logout)
    Button btnLogout;

    private UserBean userBean;
    private String picUrl;
    private String filePath;

    private InvokeParam invokeParam;
    private TakePhoto takePhoto;

    private UploadManager uploadManager;
    private int mSecretNumber = 0;
    private static final long MIN_CLICK_INTERVAL = 600;
    private long mLastClickTime;

    public static FragmentSettings newInstance() {
        return new FragmentSettings();
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_settings;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        userBean = ((GuideMainActivity) getActivity()).getUserBean();
        if (userBean != null) {

        } else {
            SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

                @Override
                public void onNext(BaseResponse response) {
                    if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                        userBean = (UserBean) JsonUtil.getObject(response.getReturnContent(), UserBean.class);
                        bindData();
                    }
                }
            };
            ApiMethodGuide.getStaffInfo(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getUserId(), this, FragmentEvent.DESTROY_VIEW);
        }
        Configuration config = new Configuration.Builder().zone(AutoZone.autoZone).build();
        uploadManager = new UploadManager(config);
    }

    @Override
    public void initView() {
        ntb.setTitleText("设置");
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        bindData();
        layoutVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long currentClickTime = SystemClock.uptimeMillis();
                long elapsedTime = currentClickTime - mLastClickTime;
                mLastClickTime = currentClickTime;
                if (elapsedTime < MIN_CLICK_INTERVAL) {
                    ++mSecretNumber;
                    if (9 == mSecretNumber) {
                        try {
                            start(FragmentDebug.newInstance());
                        } catch (Exception e) {
                            Log.i(getPageTag(), e.toString());
                        }
                    }
                } else {
                    mSecretNumber = 0;
                }
            }
        });
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentSettings.class.getName();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }


    private void bindData() {
        if (userBean != null) {
            tvNickname.setText(userBean.getStaffNickName());
            tvPhone.setText(userBean.getMobileNum());
            tvRealName.setText(userBean.getStaffName());
            tvShopName.setText(userBean.getStoreName());
            ImageLoaderUtils.displayCircle(mContext, ivAvatar, userBean.getStaffHeadPicUrl());
        }
        tvVersion.setText("V" + AppUtils.getAppVersionName());
    }


    private void sendRequestGetQiniuToken() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    QiniuInfo qiniuInfo = (QiniuInfo) JsonUtil.getObject(response.getReturnContent(), QiniuInfo.class);
                    String token = qiniuInfo.getUploadToken();
                    final String domain = qiniuInfo.getPathUrl();//http://static.storeer.com/appuser/headpic/
                    String key = AppConstant.QINIU_PATH + System.currentTimeMillis() + "_android_" + BizUtil.getRandomName(3) + AppConstant.PNG;
                    uploadManager.put(filePath, key, token, new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            try {
                                picUrl = domain + "/" + response.getString("key");
                                saveUserInfo(null, picUrl);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, null);
                } else {
                    ToastUtils.showShort("暂时不能上传头像");
                }
            }
        };
        ApiMethodGuide.getQiniuToken(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void saveUserInfo(final String nickName, final String picUrl) {
        HashMap hashMap = new HashMap();
        hashMap.put("staffCode", UserConfigManager.getInstance(mContext).getUserId());
        if (nickName != null) {
            hashMap.put("staffNickName", nickName);
        } else {
            hashMap.put("staffNickName", tvNickname.getText().toString());
        }
        if (picUrl != null) {
            hashMap.put("staffHeadPicUrl", picUrl);
        }
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    ToastUtils.showShort("保存成功");
                    uploadInfoSuccess(nickName, picUrl);
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {
            @Override
            public void onSessionOutOfDate() {

            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort("上传失败" + error);
            }
        };
        ApiMethodGuide.saveUserInfo(new SimpleLbObserver(listener, errorListener), body, this, FragmentEvent.DESTROY_VIEW);
    }

    private void clearNotification() {
        NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancelAll();
    }

    private void logoutSuccess() {
        mUserConfigManager.setUserId("");
        mUserConfigManager.setUserToken("");
        mUserConfigManager.setAccId("");
        mUserConfigManager.setImToken("");
        mUserConfigManager.save2Sp(true);
        JPushInterface.deleteAlias(mContext, AppConstant.SEQUENCE_SET_ALIAS);
        JPushInterface.cleanTags(mContext, AppConstant.SEQUENCE_CLEAN_TAGS);
        JPushInterface.setMobileNumber(mContext, AppConstant.SEQUENCE_SET_MOBILENUMBER, "");
        getActivity().finish();
        Intent intent = new Intent(mContext, GuideActivity.class);
        intent.putExtra(AppConstant.INTENT_KEY_FROM_LOGOUT, true);
        startActivity(intent);
    }

    private void uploadInfoSuccess(String nickName, String picUrl) {
        if (nickName != null) {
            userBean.setStaffNickName(nickName);
            tvNickname.setText(nickName);
            mUserConfigManager.setUserName(nickName);
        }
        if (picUrl != null) {
            ImageLoaderUtils.displayCircle(mContext, ivAvatar, picUrl);
            userBean.setStaffHeadPicUrl(picUrl);
            mUserConfigManager.setUserImageUrl(picUrl);
        }
        mUserConfigManager.save2Sp(true);
        EventBus.getDefault().post(new UserInfoChangeEvent(userBean));
    }

    private CropOptions getCropOptions() {
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(1).setOutputY(1);
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    private void configCompress(TakePhoto takePhoto) {
        int height = 480;
        int width = 360;
        int maxSize = 204800;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxHeight(height)
                .setMaxWidth(width)
                .setMaxSize(maxSize)
                .create();
        CompressConfig config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, true);
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(true);
        takePhoto.setTakePhotoOptions(builder.create());
    }

    @OnClick(R.id.btn_logout)
    void logout() {
        clearNotification();
        logoutSuccess();
        LogoutHelper.logout();
    }

    @OnClick(R.id.rl_avatar)
    void avatarClick() {
        SelectPicUtil.showDialogSelectPic("修改头像", mOnSelectPhotoListener, this);
    }

    @OnClick(R.id.layout_clear_cache)
    void clearCache() {
        CacheDiskUtils.getInstance().clear();
        GlideCleanUtil.getInstance().clearImageAllCache(mContext);
        ToastUtils.showShort("清除图片缓存成功");
    }



    @OnClick(R.id.rl_nickname)
    void nicknameClick() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_enter_nickname, null);
        final EditText etNickName = view.findViewById(R.id.et_nickname);
        etNickName.setText(userBean.getStaffNickName());
        etNickName.setSelection(userBean.getStaffNickName().length());//将光标移至文字末尾
        android.support.v7.app.AlertDialog dialog = new android.support.v7.app.AlertDialog.Builder(mContext).setTitle(" ")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String nickName = etNickName.getText().toString();
                        if (!TextUtils.isEmpty(nickName)) {
                            int length = LbStringUtils.getWordCount(nickName);
                            if (length < 4) {
                                ToastUtils.showShort("用户名要大于4个字符");
                                return;
                            }
                            if (length > 20) {
                                ToastUtils.showShort("用户名要小于20个字符");
                                return;
                            }
                            if (BizUtil.isUsername(nickName)) {
                                saveUserInfo(nickName, null);
                            } else {
                                ToastUtils.showShort("请输入正确的用户名");
                            }
                        }
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setView(view).create();
        dialog.show();
    }

    private DialogSelectPic.OnSelectPhotoListener mOnSelectPhotoListener = new DialogSelectPic.OnSelectPhotoListener() {
        @Override
        public void onTakePhoto(int id, boolean ifCrop) {
            File file = new File(AppConfigManager.DIR_IMAGE + System.currentTimeMillis() + AppConstant.JPG); // 存放路径
            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            Uri imageUri = Uri.fromFile(file);

            configCompress(takePhoto);
            configTakePhotoOption(takePhoto);
            switch (id) {
                case R.id.rl_profile_take_photo:
                    takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
                    break;
                case R.id.rl_profile_local_photo:
                    takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
                    break;
            }
        }
    };

    @Override
    public void takeSuccess(TResult result) {
        filePath = result.getImage().getCompressPath();
        if (!TextUtils.isEmpty(filePath)) {
            sendRequestGetQiniuToken();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
    }

    @Override
    public void takeCancel() {
        ToastUtils.showShort("取消");
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }
}
